import React, { useState, useEffect, useCallback } from 'react';
import { RoomStatusManager } from '../utils/RoomStatusManager';
import type { Room } from '../../../types/room';
import { RoomStatus } from '../../../types/room';
import styles from '../styles/DragOperationFeedback.module.css';

// 操作反馈类型
export type FeedbackType = 'success' | 'error' | 'warning' | 'info';

export interface OperationFeedback {
  id: string;
  type: FeedbackType;
  title: string;
  message: string;
  details?: string;
  duration?: number;
  actions?: Array<{
    label: string;
    onClick: () => void;
    type?: 'primary' | 'secondary';
  }>;
  icon?: string;
  sourceRoom?: Room;
  targetRoom?: Room;
  sourceDate?: string;
  targetDate?: string;
  status?: RoomStatus;
}

interface DragOperationFeedbackProps {
  feedbacks: OperationFeedback[];
  onRemoveFeedback: (id: string) => void;
  onActionClick?: (feedbackId: string, actionIndex: number) => void;
  position?:
    | 'top-right'
    | 'top-left'
    | 'bottom-right'
    | 'bottom-left'
    | 'center';
  maxVisible?: number;
}

const DragOperationFeedback: React.FC<DragOperationFeedbackProps> = ({
  feedbacks,
  onRemoveFeedback,
  onActionClick,
  position = 'top-right',
  maxVisible = 5,
}) => {
  const [visibleFeedbacks, setVisibleFeedbacks] = useState<OperationFeedback[]>(
    []
  );
  const [animatingOut, setAnimatingOut] = useState<Set<string>>(new Set());

  // 管理可见的反馈
  useEffect(() => {
    setVisibleFeedbacks(feedbacks.slice(0, maxVisible));
  }, [feedbacks, maxVisible]);

  // 自动移除反馈
  useEffect(() => {
    const timers: NodeJS.Timeout[] = [];

    visibleFeedbacks.forEach(feedback => {
      if (feedback.duration && feedback.duration > 0) {
        const timer = setTimeout(() => {
          handleRemoveFeedback(feedback.id);
        }, feedback.duration);
        timers.push(timer);
      }
    });

    return () => {
      timers.forEach(timer => clearTimeout(timer));
    };
  }, [visibleFeedbacks]);

  // 处理移除反馈
  const handleRemoveFeedback = useCallback(
    (id: string) => {
      setAnimatingOut(prev => new Set([...prev, id]));

      setTimeout(() => {
        onRemoveFeedback(id);
        setAnimatingOut(prev => {
          const newSet = new Set(prev);
          newSet.delete(id);
          return newSet;
        });
      }, 300);
    },
    [onRemoveFeedback]
  );

  // 处理动作点击
  const handleActionClick = useCallback(
    (feedbackId: string, actionIndex: number) => {
      if (onActionClick) {
        onActionClick(feedbackId, actionIndex);
      }
    },
    [onActionClick]
  );

  // 获取反馈图标
  const getFeedbackIcon = (feedback: OperationFeedback): string => {
    if (feedback.icon) return feedback.icon;

    switch (feedback.type) {
      case 'success':
        return '✅';
      case 'error':
        return '❌';
      case 'warning':
        return '⚠️';
      case 'info':
        return 'ℹ️';
      default:
        return '📝';
    }
  };

  // 获取反馈样式类
  const getFeedbackClass = (feedback: OperationFeedback): string => {
    const baseClass = styles.feedback;
    const typeClass = styles[feedback.type];
    const animatingClass = animatingOut.has(feedback.id)
      ? styles.animatingOut
      : '';

    return [baseClass, typeClass, animatingClass].filter(Boolean).join(' ');
  };

  // 渲染房间信息
  const renderRoomInfo = (room: Room, date?: string) => (
    <div className={styles.roomInfo}>
      <span className={styles.roomNumber}>{room.roomNumber}</span>
      <span className={styles.roomType}>{room.roomType}</span>
      {date && <span className={styles.date}>{date}</span>}
    </div>
  );

  // 渲染状态信息
  const renderStatusInfo = (status: RoomStatus) => {
    const statusConfig = RoomStatusManager.getStatusConfig(status);
    return (
      <div className={styles.statusInfo}>
        <span className={styles.statusIcon}>{statusConfig.icon}</span>
        <span className={styles.statusLabel}>{statusConfig.label}</span>
      </div>
    );
  };

  if (visibleFeedbacks.length === 0) {
    return null;
  }

  return (
    <div className={`${styles.feedbackContainer} ${styles[position]}`}>
      {visibleFeedbacks.map((feedback, index) => (
        <div
          key={feedback.id}
          className={getFeedbackClass(feedback)}
          style={{
            zIndex: 1000 + index,
            animationDelay: `${index * 100}ms`,
          }}
        >
          {/* 头部 */}
          <div className={styles.feedbackHeader}>
            <div className={styles.feedbackIcon}>
              {getFeedbackIcon(feedback)}
            </div>
            <div className={styles.feedbackTitle}>{feedback.title}</div>
            <button
              className={styles.closeButton}
              onClick={() => handleRemoveFeedback(feedback.id)}
              aria-label='关闭'
            >
              ×
            </button>
          </div>

          {/* 内容 */}
          <div className={styles.feedbackContent}>
            <div className={styles.feedbackMessage}>{feedback.message}</div>

            {/* 详细信息 */}
            {feedback.details && (
              <div className={styles.feedbackDetails}>{feedback.details}</div>
            )}

            {/* 房间信息展示 */}
            {(feedback.sourceRoom || feedback.targetRoom) && (
              <div className={styles.roomsContainer}>
                {feedback.sourceRoom && (
                  <div className={styles.sourceRoom}>
                    <div className={styles.roomLabel}>源房间:</div>
                    {renderRoomInfo(feedback.sourceRoom, feedback.sourceDate)}
                  </div>
                )}

                {feedback.sourceRoom && feedback.targetRoom && (
                  <div className={styles.arrow}>→</div>
                )}

                {feedback.targetRoom && (
                  <div className={styles.targetRoom}>
                    <div className={styles.roomLabel}>目标房间:</div>
                    {renderRoomInfo(feedback.targetRoom, feedback.targetDate)}
                  </div>
                )}
              </div>
            )}

            {/* 状态信息 */}
            {feedback.status && (
              <div className={styles.statusContainer}>
                <div className={styles.statusLabel}>当前状态:</div>
                {renderStatusInfo(feedback.status)}
              </div>
            )}
          </div>

          {/* 操作按钮 */}
          {feedback.actions && feedback.actions.length > 0 && (
            <div className={styles.feedbackActions}>
              {feedback.actions.map((action, actionIndex) => (
                <button
                  key={actionIndex}
                  className={`${styles.actionButton} ${styles[action.type || 'secondary']}`}
                  onClick={() => {
                    action.onClick();
                    handleActionClick(feedback.id, actionIndex);
                  }}
                >
                  {action.label}
                </button>
              ))}
            </div>
          )}

          {/* 进度条（用于显示自动消失倒计时） */}
          {feedback.duration && feedback.duration > 0 && (
            <div className={styles.progressContainer}>
              <div
                className={styles.progressBar}
                style={{
                  animationDuration: `${feedback.duration}ms`,
                }}
              />
            </div>
          )}
        </div>
      ))}

      {/* 显示更多指示器 */}
      {feedbacks.length > maxVisible && (
        <div className={styles.moreIndicator}>
          还有 {feedbacks.length - maxVisible} 条消息
        </div>
      )}
    </div>
  );
};

// Hook for managing drag operation feedback
export const useDragOperationFeedback = () => {
  const [feedbacks, setFeedbacks] = useState<OperationFeedback[]>([]);

  const addFeedback = useCallback((feedback: Omit<OperationFeedback, 'id'>) => {
    const newFeedback: OperationFeedback = {
      ...feedback,
      id: `feedback-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      duration: feedback.duration ?? 5000, // 默认5秒
    };

    setFeedbacks(prev => [newFeedback, ...prev]);
    return newFeedback.id;
  }, []);

  const removeFeedback = useCallback((id: string) => {
    setFeedbacks(prev => prev.filter(f => f.id !== id));
  }, []);

  const clearAllFeedbacks = useCallback(() => {
    setFeedbacks([]);
  }, []);

  // 便捷方法
  const showSuccess = useCallback(
    (title: string, message: string, options?: Partial<OperationFeedback>) => {
      return addFeedback({ type: 'success', title, message, ...options });
    },
    [addFeedback]
  );

  const showError = useCallback(
    (title: string, message: string, options?: Partial<OperationFeedback>) => {
      return addFeedback({
        type: 'error',
        title,
        message,
        duration: 8000,
        ...options,
      });
    },
    [addFeedback]
  );

  const showWarning = useCallback(
    (title: string, message: string, options?: Partial<OperationFeedback>) => {
      return addFeedback({
        type: 'warning',
        title,
        message,
        duration: 6000,
        ...options,
      });
    },
    [addFeedback]
  );

  const showInfo = useCallback(
    (title: string, message: string, options?: Partial<OperationFeedback>) => {
      return addFeedback({ type: 'info', title, message, ...options });
    },
    [addFeedback]
  );

  // 拖拽操作特定反馈
  const showDragSuccess = useCallback(
    (
      sourceRoom: Room,
      targetRoom: Room,
      sourceDate: string,
      targetDate: string,
      status: RoomStatus
    ) => {
      return showSuccess('拖拽成功', '房间状态已成功移动', {
        sourceRoom,
        targetRoom,
        sourceDate,
        targetDate,
        status,
        icon: '🎯',
        actions: [
          {
            label: '撤销',
            type: 'secondary',
            onClick: () => {
              // 这里可以添加撤销逻辑
              console.log('撤销拖拽操作');
            },
          },
        ],
      });
    },
    [showSuccess]
  );

  const showDragError = useCallback(
    (sourceRoom: Room, targetRoom: Room, reason: string) => {
      return showError('拖拽失败', reason, {
        sourceRoom,
        targetRoom,
        icon: '🚫',
        actions: [
          {
            label: '重试',
            type: 'primary',
            onClick: () => {
              // 这里可以添加重试逻辑
              console.log('重试拖拽操作');
            },
          },
        ],
      });
    },
    [showError]
  );

  return {
    feedbacks,
    addFeedback,
    removeFeedback,
    clearAllFeedbacks,
    showSuccess,
    showError,
    showWarning,
    showInfo,
    showDragSuccess,
    showDragError,
  };
};

export default DragOperationFeedback;
